﻿using CoreShop.App.Properties;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Windows.Forms;

namespace CoreShop.App
{
    public partial class frmFoodSoldoutList : UIForm
    {
        public frmFoodSoldoutList()
        {
            InitializeComponent();
            this.ShowFullScreen = AppConstVars.showFullScreen;
        }

        private int mTypePageIndex = 1;//分类页码
        private int mTypePageSize = 10;//分类页码大小
        private int mTypeRowCount = 0;//分类数据条数        

        private int mFoodPageIndex = 1;//商品页码
        private int mFoodPageSize = 10;//商品页码大小
        private int mFoodRowCount = 0;//商品数据条数      
        private long mFoodTypeId = 0;//商品分类ID，分组用
        private List<corecmsfoodsoldout> foodSoldouts;

        #region 控件机关

        /// <summary>
        /// 根据指定容器和控件名字，获得控件
        /// </summary>
        /// <param name="obj">容器</param>
        /// <param name="strControlName">控件名字</param>
        /// <returns>控件</returns>
        private object GetControlInstance(object obj, string strControlName)
        {
            IEnumerator Controls = null;//所有控件
            Control c = null;//当前控件
            Object cResult = null;//查找结果
            if (obj.GetType() == this.GetType())//窗体
            {
                Controls = this.Controls.GetEnumerator();
            }
            else//控件
            {
                Controls = ((Control)obj).Controls.GetEnumerator();
            }
            while (Controls.MoveNext())//遍历操作
            {
                c = (Control)Controls.Current;//当前控件
                if (c.HasChildren)//当前控件是个容器
                {
                    cResult = GetControlInstance(c, strControlName);//递归查找
                    if (cResult == null)//当前容器中没有，跳出，继续查找
                        continue;
                    else//找到控件，返回
                        return cResult;
                }
                else if (c.Name == strControlName)//不是容器，同时找到控件，返回
                {
                    return c;
                }
            }
            return null;//控件不存在
        }

        private string GetMenuItemName(long orderingId)
        {
            return "uiMenuItem_" + orderingId.ToString();
        }

        private string GetFoodTypeButtonName(long foodTypeId)
        {
            return "btnFoodType_" + foodTypeId.ToString();
        }

        #endregion

        private void FOrdering_Load(object sender, EventArgs e)
        {
            CreateFoodType();
            BindFoodType();

            CreateFoodList();
            LoadDataList();
        }

        #region 加载信息列表
        private void LoadDataList()
        {
            var soldoutServices = new corecmsfoodsoldoutServices();
            foodSoldouts = soldoutServices.QueryFoodSoldouts();
            //加载重置按营业日类型的估清配置
            new corecmsfoodsoldoutServices().RecoverySoldout((int)GlobalEnumVars.SoldoutType.Day, foodSoldouts);
            this.dgvFoodList.AutoGenerateColumns = false;
            this.dgvFoodList.DataSource = foodSoldouts;

            lblSoldoutMsg.Text = string.Format("设置沽清商品数：{0}个", foodSoldouts.Count);
        }
        #endregion

        private void Form1_Shown(object sender, System.EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            BindFoodList(0);
        }

        #region 商品分类按钮及数据

        private void CreateFoodTypeBtn(int index, ref int mLeft, int mTop)
        {
            UIButton btn = new UIButton();
            btn.Name = "btnFoodType_" + index.ToString();
            btn.Parent = pnl_center_top_foodtype1;
            btn.Tag = index;
            btn.Left = mLeft;
            btn.Top = mTop;
            btn.Text = "商品分类" + index.ToString();
            btn.BackColor = btnFoodType_1.BackColor;
            btn.Cursor = btnFoodType_1.Cursor;
            btn.FillColor = btnFoodType_1.FillColor;
            btn.FillColor2 = btnFoodType_1.FillColor2;
            btn.FillHoverColor = btnFoodType_1.FillHoverColor;
            btn.FillPressColor = btnFoodType_1.FillPressColor;
            btn.FillSelectedColor = btnFoodType_1.FillSelectedColor;
            btn.Font = btnFoodType_1.Font;
            btn.ForeHoverColor = btnFoodType_1.ForeHoverColor;
            btn.ForePressColor = btnFoodType_1.ForePressColor;
            btn.ForeSelectedColor = btnFoodType_1.ForeSelectedColor;
            btn.MinimumSize = btnFoodType_1.MinimumSize;
            btn.Radius = btnFoodType_1.Radius;
            btn.RectColor = btnFoodType_1.RectColor;
            btn.RectHoverColor = btnFoodType_1.RectHoverColor;
            btn.RectPressColor = btnFoodType_1.RectPressColor;
            btn.RectSelectedColor = btnFoodType_1.RectSelectedColor;
            btn.Size = btnFoodType_1.Size;
            btn.Style = btnFoodType_1.Style;
            btn.StyleCustomMode = btnFoodType_1.StyleCustomMode;
            btn.TipsFont = btnFoodType_1.TipsFont;
            btn.ForeColor = btnFoodType_1.ForeColor;
            btn.TipsColor = btnFoodType_1.TipsColor;
            btn.TipsForeColor = btnFoodType_1.TipsForeColor;
            btn.ShowTips = btnFoodType_1.ShowTips;
            btn.Click += this.btnFoodType_1_Click;
            mLeft = btn.Left + btn.Width + 2;
        }

        private void CreateFoodType()
        {
            decimal btnCounts = pnl_center_top_foodtype.Width / btnFoodType_1.Width;
            int mRowSize = CommFunc.ConvertToInt32(Math.Floor(btnCounts)) - 3;
            int mLeft = btnFoodType_1.Left + btnFoodType_1.Width + 2;
            int mTop = btnFoodType_1.Top;
            mTypePageSize = mRowSize * 2 + 1;
            for (int i = 2; i <= mTypePageSize; i++)
            {
                if (i == mRowSize + 1)
                {
                    mLeft = btnAllType.Left;
                    mTop = btnFoodType_1.Top + btnFoodType_1.Height + 15;
                }
                CreateFoodTypeBtn(i, ref mLeft, mTop);
            }
        }

        private void CleareFoodTypeBtn()
        {
            for (int i = 1; i <= mTypePageSize; i++)
            {
                string btnName0 = "btnFoodType_" + i.ToString();
                UIButton btnType = (UIButton)GetControlInstance(this, btnName0);
                if (btnType != null) btnType.Visible = false;
            }
        }

        private void SetFoodTypeUnSelect()
        {
            for (int i = 1; i <= mTypePageSize; i++)
            {
                string btnName0 = "btnFoodType_" + i.ToString();
                UIButton btnType = (UIButton)GetControlInstance(this, btnName0);
                if (btnType != null) btnType.Selected = false;
            }
        }

        private void SetFoodTypePageState()
        {
            if (mTypeRowCount <= mTypePageSize)
            {
                btnFoodTypePre.Enabled = false;
                btnFoodTypeNext.Enabled = false;
            }
            else if (mTypePageIndex == 1)
            {
                btnFoodTypePre.Enabled = false;
                btnFoodTypeNext.Enabled = true;
            }
            else if (mTypePageIndex * mTypePageSize > mTypeRowCount)
            {
                btnFoodTypePre.Enabled = true;
                btnFoodTypeNext.Enabled = false;
            }
            else
            {
                btnFoodTypePre.Enabled = true;
                btnFoodTypeNext.Enabled = true;
            }
        }

        private void SetFoodTypeTips(long mTypeId)
        {
            for (int i = 1; i <= mTypePageSize; i++)
            {
                string btnName0 = "btnFoodType_" + i.ToString();
                UIButton btnType = (UIButton)GetControlInstance(this, btnName0);
                if (CommFunc.ConvertToBtInt(btnType.Tag) == mTypeId)
                {


                }
            }
        }

        private void BindFoodType()
        {
            CleareFoodTypeBtn();
            int btnIndex = 1;
            if (mTypePageIndex < 1) mTypePageIndex = 1;
            var typeList = new corecmsfoodcategoryServices().QueryPageAsync(ref mTypeRowCount, mTypePageIndex, mTypePageSize, "", AppConstVars.sysStore);
            foreach (var item in typeList)
            {
                string btnName = GetFoodTypeButtonName(btnIndex);
                try
                {
                    UIButton btnType = (UIButton)GetControlInstance(this, btnName);
                    btnType.Tag = item.id.ToString();
                    btnType.Text = item.name;
                    btnType.Visible = true;
                    //if ((btnIndex == 3) || (btnIndex == 7))
                    //{
                    //    btnType.TipsText = btnIndex.ToString();
                    //}
                }
                catch { }
                btnIndex += 1;
            }
            SetFoodTypePageState();
        }

        #endregion

        #region 加载商品资料

        /// <summary>
        /// 商品按钮名称
        /// </summary>
        /// <param name="deskId"></param>
        /// <returns></returns>
        private string GetFoodItemName(int index)
        {
            return "uiFoodItem_" + index.ToString();
        }

        /// <summary>
        /// 建空的单个商品按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreateFoodListBtn(int index)
        {
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "";
            //dish.Money = food.posPrice.ToString()+"/"+ food.foodSpecName;
            dish.Money = "";
            dish.UnitName = "";
            //if (food.isHeft.ObjToBool())
            //{
            //    dish.LabelExist = "剩 10,000 份";
            //    dish.DiscountString = "3个优惠";
            //}
            var item = new UIDishItem(dish);
            item.Name = GetFoodItemName(index);
            item.Visible = false;
            if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
            //item.TipsText = RandomEx.RandomNumber(1);
            item.Margin = new System.Windows.Forms.Padding(3);
            item.Tag = "";
            item.Click += Item_Click;
            fly_foodlist.Add(item);
        }

        /// <summary>
        /// 建空的商品按钮
        /// </summary>
        private void CreateFoodList()
        {
            fly_foodlist.Clear();
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "默认";
            dish.Money = "0.00";
            dish.UnitName = "";
            var item = new UIDishItem(dish);

            if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
            item.Margin = new System.Windows.Forms.Padding(3);
            decimal itemCols = (fly_foodlist.Width - 10) / (item.Width + 3);
            decimal itemRows = (fly_foodlist.Height - 10) / (item.Height + 3);

            mFoodPageSize = CommFunc.ConvertToInt32(Math.Floor(itemCols)) * CommFunc.ConvertToInt32(Math.Floor(itemRows));
            for (int i = 1; i <= mFoodPageSize; i++)
            {
                CreateFoodListBtn(i);
            }
        }

        private void SetFoodListPageState()
        {
            if (mFoodRowCount <= mFoodPageSize)
            {
                btnFoodListPre.Enabled = false;
                btnFoodListNext.Enabled = false;
            }
            else if (mFoodPageIndex == 1)
            {
                btnFoodListPre.Enabled = false;
                btnFoodListNext.Enabled = true;
            }
            else if (mFoodPageIndex * mFoodPageSize > mFoodRowCount)
            {
                btnFoodListPre.Enabled = true;
                btnFoodListNext.Enabled = false;
            }
            else
            {
                btnFoodListPre.Enabled = true;
                btnFoodListNext.Enabled = true;
            }
        }


        /// <summary>
        /// 暂不显示所有商品商品
        /// </summary>
        private void HiddenFoodList(int starIndex)
        {
            for (int i = starIndex; i <= mFoodPageSize; i++)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(i));
                var item = (UIDishItem)mControl;
                if (item != null) item.Visible = false;
            }
        }

        private Expressionable<corecmsfood, corecmsfoodspec> GetExpressionable(long mFoodTypeId)
        {
            var where = Expressionable.Create<corecmsfood, corecmsfoodspec>();
            where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0 && s.onLine == true);

            string sName = txtInput.Text;
            if (!string.IsNullOrEmpty(sName))
                where = where.And((f, s) => f.name.Contains(sName) || f.number.Contains(sName) || s.code.Contains(sName)
                || f.byName.Contains(sName) || f.helpCode.Contains(sName) || f.pinYin.Contains(sName));

            if (mFoodTypeId > 0)
            {
                var typeIds = new corecmsfoodcategoryServices().AsQueryable()
                .Where(p => p.parentId == mFoodTypeId).Select(p => p.id).ToList();

                if (typeIds.Count > 0)
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId || typeIds.Contains(f.foodTypeId));
                else
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId);
            }

            return where;
        }

        private void BindFoodList(long mFoodTypeId)
        {
            if (mFoodPageIndex < 1) mFoodPageIndex = 1;
            var foodList = new corecmsfoodServices().QueryPageAsync(ref mFoodRowCount, mFoodPageIndex, mFoodPageSize, GetExpressionable(mFoodTypeId));
            int index = 1;
            fly_foodlist.Visible = false;
            foreach (var food in foodList)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(index));
                var item = (UIDishItem)mControl;
                if (item != null)
                {
                    item.Visible = true;
                    item.TextName = food.name;
                    var dish = item.Info;
                    dish.Name = food.name;
                    dish.Money = food.posPrice.ToString();
                    var foodSoldout = foodSoldouts.Find(p => p.foodSpecId == food.foodSpecId);
                    if (foodSoldout != null)
                    {
                        dish.LabelExist = string.Format("剩{0}{1}", CommFunc.FormatDecimal(foodSoldout.soldout), food.foodSpecName);
                    }
                    else
                    {
                        dish.LabelExist = "";
                    }

                    if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
                    //item.TipsText = RandomEx.RandomNumber(1);
                    item.Tag = food.id.ToString();
                    item.Refresh();
                }
                index++;
            }
            HiddenFoodList(index);
            fly_foodlist.Visible = true;
            SetFoodListPageState();
        }

        /// <summary>
        /// 旧的实时查询数据库及实时创建方法(弃用)
        /// </summary>
        /// <param name="mFoodTypeId"></param>
        private void BindFoodList_Old(long mFoodTypeId)
        {
            fly_foodlist.Clear();
            int count = 0;
            var foodList = new corecmsfoodServices().QueryPageAsync(ref count, 1, 500, GetExpressionable(mFoodTypeId));

            foreach (var food in foodList)
            {
                DishItemInfo dish = new DishItemInfo();
                dish.Name = food.name;
                //dish.Money = food.posPrice.ToString()+"/"+ food.foodSpecName;
                dish.Money = food.posPrice.ToString();
                if (food.isHeft.ObjToBool())
                {
                    dish.LabelExist = "剩 10,000 份";
                    dish.DiscountString = "3个优惠";
                }
                dish.UnitName = "";
                var item = new UIDishItem(dish);
                if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
                //item.TipsText = RandomEx.RandomNumber(1);
                item.Margin = new System.Windows.Forms.Padding(3);
                item.Tag = food.id.ToString();
                item.Click += Item_Click;
                fly_foodlist.Add(item);
            }
        }

        #endregion

        private void Item_Click(object sender, System.EventArgs e)
        {
            UIDishItem item = (UIDishItem)sender;
            SetFoodSoldoutEdit(CommFunc.ConvertToBigInt(item.Tag));
        }

        private void SetFoodSoldoutEdit(long foodId)
        {
            //判断是否多规格
            var specModel = ProcessUtil.CreateSpecByFoodId(foodId);

            if (specModel != null)
            {
                var frm = new frmFoodSoldoutEdit(specModel);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    LoadDataList();
                    //刷新右侧商品列表
                    BindFoodList(0);

                }
                frm.Disabled();
            }
        }

        private void btnAllType_Click(object sender, EventArgs e)
        {
            SetFoodTypeUnSelect();
            mTypePageIndex = 1;
            mFoodTypeId = 0;
            BindFoodList(0);
        }

        private void btnGotoTables_Click(object sender, EventArgs e)
        {
           // Program.frmMainWin.ShowTables();
        }

        private void sbtHome_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void btnFoodType_1_Click(object sender, EventArgs e)
        {
            var btn = (UIButton)sender;
            btn.Selected = true;
            mFoodPageIndex = 1;
            mFoodTypeId = CommFunc.ConvertToInt64(btn.Tag);
            BindFoodList(mFoodTypeId);
        }

        private void btnFoodTypeNext_Click(object sender, EventArgs e)
        {
            mTypePageIndex += 1;
            BindFoodType();
        }

        private void btnFoodTypePre_Click(object sender, EventArgs e)
        {
            mTypePageIndex -= 1;
            BindFoodType();
        }

        private void btnRemark_Click(object sender, EventArgs e)
        {
            var frm = new FButtons();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void FOrdering_Activated(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void dgvFoodList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvFoodList.SelectedRows.Count == 1)
            {
                long foodId = CommFunc.ConvertToInt64(dgvFoodList.SelectedRows[0].Cells["foodId"].Value);
                SetFoodSoldoutEdit(foodId);
            }
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            if (!ShowAskDialog("确定要清空当前所有沽清吗？")) return;
            var bl = new corecmsfoodsoldoutServices().Delete(p => p.id > 0);
            if (!bl)
            {
                UIMessageBox.Show("提交保存失败。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            LoadDataList();
            BindFoodList(0);
            UIMessageBox.Show("清空完成", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
        }

        private void txtInput_ValueChanged(object sender, string value)
        {
            mFoodPageIndex = 1;
            BindFoodList(0);
        }

        private void btnFoodListPre_Click(object sender, EventArgs e)
        {
            mFoodPageIndex -= 1;
            BindFoodList(mFoodTypeId);
        }

        private void btnFoodListNext_Click(object sender, EventArgs e)
        {
            mFoodPageIndex += 1;
            BindFoodList(mFoodTypeId);
        }
    }
}